import { Fragment } from 'react';
import { Table, Space } from 'antd';

import getUpdateOperator from './update.operator'
import getDeleteOperator from './delete.operator'

const { Column } = Table

function getOperatorColumn(
  showUModal,
  del,
  successCallback,
  otherOperators,
  others = {},
  title = '操作',
  key = 'operator',
  dataIndex = 'operator',
) {

  return (
    <Column {...others}  title={title} dataIndex={dataIndex} key={key} render={(text, record) => {
      return (
        <Space size="middle">
          {defaultRender(text, record, showUModal, del, successCallback, otherOperators)}
        </Space>
      )
    }} />
  )
}

function getOtherOperator(
  record,
  // 其它操作：格式为{name: '', icon: '', onClick: func, getName: func, disabled: false}，数组
  // 注意，其中的onClick和getName方法需要是一个闭包，返回一个函数
  otherOperators,
) {
  if (!otherOperators || otherOperators.length < 1) return null
  return otherOperators.map((operator, index) =>
    <a key={index} disabled={operator.disabled} onClick={operator.onClick(record)}>
      {operator.icon}&nbsp;{operator.name || operator.getName(record)}
    </a>
  )
}

function defaultRender(_, record, showUModal, del, successCallback, otherOperators) {
  const updateOperator = getUpdateOperator(showUModal, record)
  const deleteOperator = getDeleteOperator(del, successCallback, record)
  const operators = getOtherOperator(record, otherOperators)
  // 使用下面的方法可以避免警告 => Cell没有key
  // return operators ? [updateOperator, ...operators, deleteOperator] : [updateOperator, deleteOperator]
  const allOperators = operators ? [updateOperator, ...operators, deleteOperator] : [updateOperator, deleteOperator]
  return (
    <>
      {
        allOperators.map((operator, index) =>
          <Fragment key={index}>
            {operator}
          </Fragment>
        )
      }
    </>
  )
}

function getOperatorColumnByRender(
  renderCallBack,
  others = {},
  title = '操作',
  key = 'operator',
  dataIndex = 'operator',
) {
  return (
    <Column {...others} title={title} dataIndex={dataIndex} key={key} render={(text, record) => {
      return (
        <Space size="middle">
          {renderCallBack(text, record).map((operator, index) =>
            <Fragment key={index}>
              {operator}
            </Fragment>
            )
          }
        </Space>
      )
    }} />
  )
}

export { getOperatorColumn, getOperatorColumnByRender, getOtherOperator }
